import React, { useState } from 'react';
import { Form, message, Modal, Spin } from 'antd';

import If from '@/components/If';
import { isSuccess } from '@/utils/request';

import { reject } from '@/services/salaryManage/salaryConfirm';
import LimitInput from '@/components/LimitInput';

const RejectModal = React.memo(
    Form.create()(({ form, visible, onOk, onCancel, model }) => {
        const [loading, setLoading] = useState(false);
        const handleOk = () => onOk(form.getFieldsValue(), form, model, setLoading);

        return (
            <Modal
                title="确定拒绝"
                visible={visible}
                okText="确认"
                onOk={handleOk}
                cancelText="取消"
                onCancel={onCancel}
                confirmLoading={loading}
            >
                <Spin spinning={loading}>
                    <Form layout="horizontal" labelCol={{ span: 5 }} wrapperCol={{ span: 18 }}>
                        <Form.Item label="理由">
                            {form.getFieldDecorator('reason', {
                                rules: [{ required: true, message: '请填写拒绝理由' }]
                            })(<LimitInput placeholder="请输入" maxLength={100} area showNumber />)}
                        </Form.Item>
                    </Form>
                </Spin>
            </Modal>
        );
    })
);
RejectModal.displayName = 'RejectModal';

const useReject = (operateRecord, setOperateRecord, search) => {
    // 是否显示【拒绝对话框】
    const [showReject, setShowReject] = useState(false);

    // 显示拒绝弹出框
    const onShowReject = record => {
        setShowReject(true);
        setOperateRecord(record);
    };
    // 执行拒绝操作
    const onReject = (formValues, form, record, setModalLoading) => {
        form.validateFieldsAndScroll(errors => {
            if (errors) {
                return;
            }
            setModalLoading(true);
            reject({ id: record.id, ...formValues })
                .then(response => {
                    if (!isSuccess(response)) {
                        message.error(response.msg);
                        return;
                    }
                    message.success('拒绝成功');
                    search();
                    setShowReject(false);
                })
                .finally(() => setModalLoading(false));
        });
    };

    return {
        onShowReject,
        onReject,
        render() {
            return (
                <>
                    <If condition={showReject}>
                        <RejectModal
                            visible={showReject}
                            onOk={onReject}
                            onCancel={() => setShowReject(false)}
                            model={operateRecord}
                        />
                    </If>
                </>
            );
        }
    };
};

export default useReject;
